import asyncio
import datetime

from aiogram import Router, F, exceptions
from aiogram import types
from aiogram.fsm.context import FSMContext
from aiogram.types import PhotoSize, FSInputFile
from aiogram.utils.markdown import hbold, hlink, hitalic

from handlers.users_message import delete_mess
from keyboards import menu_keys
from keyboards.callbacks_data import MenuCategory

from loader import logger, bot, db, scheduler
from utils import RequireChannelsStates, AdsStates

router = Router()
router.message.filter(F.chat.type == "private")

router.callback_query.filter(
    MenuCategory.filter(F.category == 'ads'),
)


@router.callback_query(MenuCategory.filter(F.action == 'add'))
async def ads_add(call: types.CallbackQuery, callback_data: MenuCategory, state: FSMContext):
    await state.set_state(AdsStates.add)
    cal = await call.message.edit_text('Перешли мне сообщение или отправь по очереди текст и картинку')
    await call.message.edit_reply_markup(menu_keys.back(2, 'ads'))
    await state.update_data(call=call)
    scheduler.add_job(state.clear, trigger='date', run_date=datetime.datetime.now() + datetime.timedelta(minutes=1))


@router.message(AdsStates.add, F.content_type == 'text')
async def ads_add_text(message: types.Message, state: FSMContext):
    data = await state.get_data()
    call: types.CallbackQuery = data['call']
    await state.update_data(text=message.text)
    await call.message.edit_text(f"{call.message.text}\n{message.text}")
    await call.message.edit_reply_markup(menu_keys.ads_done(2, 'ads'))
    logger.info(message.text)
    await message.delete()


@router.message(AdsStates.add, F.photo[-1].as_("largest_photo"))
async def ads_add_photo(message: types.Message, state: FSMContext, largest_photo: PhotoSize):
    data = await state.get_data()
    call: types.CallbackQuery = data['call']
    file = await bot.get_file(largest_photo.file_id)
    await bot.download_file(file.file_path, destination=f'data/{largest_photo.file_id}.jpg')
    text = message.caption if message.caption else data['text']
    db.add_ads(text, f'{largest_photo.file_id}')
    await message.delete()
    await state.clear()
    await show_menu(call, MenuCategory(level=1, category='ads'), state)


@router.callback_query(MenuCategory.filter(F.action == 'delete'))
async def ads_del(call: types.CallbackQuery, callback_data: MenuCategory, state: FSMContext):
    db.delete_ads(callback_data.chat_id)
    await call.answer("Успешно удалено", show_alert=True)
    await show_menu(call, MenuCategory(level=1, category='ads'), state)


@router.callback_query(AdsStates.add, MenuCategory.filter(F.action == 'done'))
async def ads_done(call: types.CallbackQuery, callback_data: MenuCategory, state: FSMContext):
    data = await state.get_data()
    text = data['text']
    db.add_ads(text)
    await state.clear()
    await show_menu(call, MenuCategory(level=1, category='ads'), state)


@router.callback_query(MenuCategory.filter(F.action == 'start'))
async def ads_start(call: types.CallbackQuery, callback_data: MenuCategory, state: FSMContext):
    # TODO rewrite this shit to scheduled send message
    chats = db.select_channels_for_ads()
    ads = db.get_ads(callback_data.chat_id)
    if ads.path_photo:
        photo = FSInputFile(path=f'data/{ads.path_photo}.jpg')
        for chat in chats:
            await bot.send_photo(chat_id=chat, photo=photo, caption=ads.text)
            await asyncio.sleep(0.1)
    else:
        for chat in chats:
            await bot.send_message(chat_id=chat, text=ads.text)
            await asyncio.sleep(0.1)
    await call.message.edit_text("Рассылка закочена")
    scheduler.add_job(show_menu, args=(call, MenuCategory(level=1, category='ads'), state),
                      trigger='date', run_date=datetime.datetime.now() + datetime.timedelta(minutes=1))


@router.callback_query()
async def show_menu(call: types.CallbackQuery, callback_data: MenuCategory, state: FSMContext):
    current_level = callback_data.level
    if callback_data.action == 'back':
        current_level -= 1

    levels = {
        0: menu_keys.admin_menu(),
        1: menu_keys.ads_list(),
        2: menu_keys.ads_action(3, 'ads', callback_data.chat_id),
        3: menu_keys.back(1, 'ads')
    }
    texts = {
        0: "Вот чем вы можете управлять:",
        1: f"{hbold('Выбери рекламу, которую хочешь запусть:')} \n\n",
        2: f"Доступны такие действия: \n",
        3: f"Видимо что-то пошло не так"
    }
    if current_level == 2:
        list_ads = db.select_all_ads()
        for ad in list_ads:
            if int(callback_data.chat_id) == ad.id:
                texts[2] = f"Текст:\n{ad.text}\n\n{texts[2]}"
                if ad.path_photo:
                    photo = await bot.send_photo(call.message.chat.id, FSInputFile(f"data/{ad.path_photo}.jpg"),
                                                 caption=ad.text + f"\n\n"
                                                                   f"{hbold('Это образец того что бот отправит по чатам')}"
                                                                   f"\n{hitalic('Сообщение удалится через минуту')}")
                    scheduler.add_job(delete_mess, args=(photo,), trigger="date",
                                      run_date=datetime.datetime.now() + datetime.timedelta(minutes=1))
    await call.message.edit_text(texts[current_level], disable_web_page_preview=True)
    await call.message.edit_reply_markup(levels[current_level])
